import { IUserInfo } from '../../../stores/types/types';
import { ref, watchEffect, Ref, UnwrapRef } from 'vue';
import { isNotEmpty } from '../utils/cy-empty';

export function useStorage<T>(name: string, defaultValue?: T) {
  const local = uni.getStorageSync(name) ?? '';
  const localData = ref<T>(null as T);

  if (isNotEmpty(local)) {
    localData.value = JSON.parse(local);
  } else if (isNotEmpty(defaultValue)) {
    localData.value = defaultValue as UnwrapRef<T>;
  }

  watchEffect(() => {
    // 监听本地localData数据对应的响应式变量更改
    uni.setStorageSync(name, JSON.stringify(localData.value));
  });

  function removeStorage() {
    uni.removeStorageSync(name);
    localData.value = null as UnwrapRef<T>;
  }

  return {
    localData,
    removeStorage,
  };
}
